package com.zhenyi.tuangou.index;

import java.util.Map;

import org.hashids.Hashids;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.iot.msg.InEquDataMsg;
import com.jfinal.weixin.iot.msg.InEqubindEvent;
import com.jfinal.weixin.sdk.jfinal.MsgController;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.msg.in.InImageMsg;
import com.jfinal.weixin.sdk.msg.in.InLinkMsg;
import com.jfinal.weixin.sdk.msg.in.InLocationMsg;
import com.jfinal.weixin.sdk.msg.in.InNotDefinedMsg;
import com.jfinal.weixin.sdk.msg.in.InShortVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.InVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InVoiceMsg;
import com.jfinal.weixin.sdk.msg.in.card.InCardPassCheckEvent;
import com.jfinal.weixin.sdk.msg.in.card.InCardPayOrderEvent;
import com.jfinal.weixin.sdk.msg.in.card.InCardSkuRemindEvent;
import com.jfinal.weixin.sdk.msg.in.card.InMerChantOrderEvent;
import com.jfinal.weixin.sdk.msg.in.card.InUpdateMemberCardEvent;
import com.jfinal.weixin.sdk.msg.in.card.InUserCardEvent;
import com.jfinal.weixin.sdk.msg.in.card.InUserConsumeCardEvent;
import com.jfinal.weixin.sdk.msg.in.card.InUserGetCardEvent;
import com.jfinal.weixin.sdk.msg.in.card.InUserGiftingCardEvent;
import com.jfinal.weixin.sdk.msg.in.card.InUserPayFromCardEvent;
import com.jfinal.weixin.sdk.msg.in.event.InCustomEvent;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InLocationEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMassEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.InNotDefinedEvent;
import com.jfinal.weixin.sdk.msg.in.event.InPoiCheckNotifyEvent;
import com.jfinal.weixin.sdk.msg.in.event.InQrCodeEvent;
import com.jfinal.weixin.sdk.msg.in.event.InShakearoundUserShakeEvent;
import com.jfinal.weixin.sdk.msg.in.event.InTemplateMsgEvent;
import com.jfinal.weixin.sdk.msg.in.event.InVerifyFailEvent;
import com.jfinal.weixin.sdk.msg.in.event.InVerifySuccessEvent;
import com.jfinal.weixin.sdk.msg.in.event.InWifiEvent;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import com.utils.interceptor.TestInterceptor;
import com.wxpay.utils.MD5Util;
import com.zhenyi.common.model.TgOrder;
import com.zhenyi.common.model.TgShop;
import com.zhenyi.core.aes.Encrypt;
import com.zhenyi.tuangou.core.OrderUtils;
import com.zhenyi.tuangou.interceptor.WXInterceptor;

import cn.hutool.core.codec.Base64;

public class WechatController extends MsgController {

	private OrderUtils orderUtils = new OrderUtils();

	private final String PARTNER_KEY = "";

	protected final Hashids hashids = new Hashids("zhenyi", 8);

	/**
	 * 微信推送订单信息
	 */
	public void billPush() {
		String xmlResult = HttpKit.readData(getRequest());
		Map<String, String> result = PaymentKit.xmlToMap(xmlResult);

		// String appid = result.get("appid");
		String bank_type = result.get("bank_type");
		String cash_fee = result.get("cash_fee");
		String fee_type = result.get("fee_type");
		String is_subscribe = result.get("is_subscribe");
		// String mch_id = result.get("mch_id");
		// String nonce_str = result.get("nonce_str");
		// String openid = result.get("openid");
		String out_trade_no = result.get("out_trade_no");
		String sign = result.get("sign");
		String time_end = result.get("time_end");
		String total_fee = result.get("total_fee");
		String trade_type = result.get("trade_type");
		String transaction_id = result.get("transaction_id");

		TgOrder order = TgOrder.dao.searchFirst("outTradeNo", out_trade_no);
		TgShop shop = order.getShop();
		String partnerKey = shop.getPartnerKey();
		String mySign = PaymentKit.createSign(result, partnerKey);
		if (!mySign.equals(sign)) {
			renderPayFail();
			return;
		} else {
		}

		orderUtils.processOrder(order);

		// order.setBankType(bank_type);
		// order.setIsSubscribe(is_subscribe);
		// order.setTradeType(trade_type);
		// order.setTransactionId(transaction_id);
		// order.setFeeType(fee_type);
		// order.setTimeEnd(time_end);
		// order.setCashFee(cash_fee);
		// order.setPaid(Integer.parseInt(total_fee));
		// order.update();

		renderPaySuccess();
	}

	// @Clear
	@Before({ TestInterceptor.class, WXInterceptor.class })
	public void test() {
		Long id = getParaToLong("id");
		TgOrder order = TgOrder.dao.findById(id);
		order.print();
		orderUtils.processOrder(order);
		renderText("ok");
	}

	/**
	 * 微信推送退款信息
	 */
	@Clear
	@Before(Tx.class)
	public void billRefund() {
		String xmlResult = HttpKit.readData(getRequest());
		if (StrKit.isBlank(xmlResult)) {
			renderPayFail();
			return;
		}
		Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
		String return_code = result.get("return_code");
		if (!"SUCCESS".equals(return_code)) {
			LogKit.warn("返回失败");
			renderPayFail();
			return;
		}

		String req_info = result.get("req_info");
		Map<String, String> refundResult = getDeResult(req_info);
		String refund_status = refundResult.get("refund_status");
		if (!"SUCCESS".equals(refund_status)) {
			renderPaySuccess();
			return;
		}
		String out_trade_no = refundResult.get("out_trade_no");
		// Long id = hashids.decode(out_trade_no)[0];
		// XhcOrder order = XhcOrder.dao.findById(id);
		// order.updateOrderStatus();
		// if ("ticket".equals(order.getAttach())) {
		// XhcUserTicket userTicket = XhcUserTicket.dao.searchFirst("orderId",
		// order.getId());
		// XhcTicket.dao.increase(userTicket.getTicketId());
		// } else if ("present".equals(order.getAttach())) {
		// XhcUserPresent userPresent =
		// XhcUserPresent.dao.searchFirst("orderId", order.getId());
		// userPresent.setStatus(-1);
		// userPresent.update();
		// XhcPresent.dao.increase(userPresent.getPresentId());
		// }
		renderPaySuccess();
	}

	private void renderPayFail() {
		String returnXML = "<xml>\n" + "<return_code><![CDATA[FAIL]]></return_code>\n"
				+ "<return_msg><![CDATA[FAIL]]></return_msg>\n" + "</xml>";
		renderText(returnXML, "text/xml");
	}

	private void renderPaySuccess() {
		String returnXML = "<xml>\n" + "<return_code><![CDATA[SUCCESS]]></return_code>\n"
				+ "<return_msg><![CDATA[OK]]></return_msg>\n" + "</xml>";
		renderText(returnXML, "text/xml");
	}

	private Map<String, String> getDeResult(String en) {
		String key = MD5Util.MD5Encode(PARTNER_KEY, "utf-8");
		String de = Encrypt.Aes256Decode(Base64.decode(en), key.getBytes());
		Map<String, String> result = PaymentKit.xmlToMap(de);
		return result;
	}

	@Override
	protected void processInCardPassCheckEvent(InCardPassCheckEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInCardPayOrderEvent(InCardPayOrderEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInCardSkuRemindEvent(InCardSkuRemindEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInCustomEvent(InCustomEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInEquDataMsg(InEquDataMsg arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInEqubindEvent(InEqubindEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInFollowEvent(InFollowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInImageMsg(InImageMsg arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInLinkMsg(InLinkMsg arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInLocationEvent(InLocationEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInLocationMsg(InLocationMsg arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInMassEvent(InMassEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInMenuEvent(InMenuEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInMerChantOrderEvent(InMerChantOrderEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInPoiCheckNotifyEvent(InPoiCheckNotifyEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInQrCodeEvent(InQrCodeEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInShakearoundUserShakeEvent(InShakearoundUserShakeEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInShortVideoMsg(InShortVideoMsg arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInSpeechRecognitionResults(InSpeechRecognitionResults arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInTemplateMsgEvent(InTemplateMsgEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInTextMsg(InTextMsg arg0) {
		OutTextMsg outTextMsg = new OutTextMsg(arg0);
		outTextMsg.setContent("111");
		render(outTextMsg);
	}

	@Override
	protected void processInUpdateMemberCardEvent(InUpdateMemberCardEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInUserCardEvent(InUserCardEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInUserConsumeCardEvent(InUserConsumeCardEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInUserGetCardEvent(InUserGetCardEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInUserGiftingCardEvent(InUserGiftingCardEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInUserPayFromCardEvent(InUserPayFromCardEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInVerifyFailEvent(InVerifyFailEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInVerifySuccessEvent(InVerifySuccessEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInVideoMsg(InVideoMsg arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInVoiceMsg(InVoiceMsg arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processInWifiEvent(InWifiEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processIsNotDefinedEvent(InNotDefinedEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processIsNotDefinedMsg(InNotDefinedMsg arg0) {
		// TODO Auto-generated method stub

	}

}
